package com.forward.uploadapp.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.forward.uploadapp.BaseActivity;
import com.forward.uploadapp.R;
import com.forward.uploadapp.adapter.GetJsonAdapter;
import com.forward.uploadapp.entity.AppInfo;
import com.forward.uploadapp.entity.AppLayout;
import com.forward.uploadapp.entity.JsonAllParse;
import com.forward.uploadapp.util.FileHelper;
import com.forward.uploadapp.util.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class GetJsonActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    private TextView mCategory;
    private ListView mListView;
    private GetJsonAdapter mAdapter;
    public List<AppInfo> mDatas;
    private JsonAllParse mJsonAllParse;
    private Map<String, List<AppInfo>> mMap;

    @Override
    public int getLayoutId() {
        return R.layout.activity_get_json;
    }

    @Override
    public void initView() {
        mCategory = ((TextView) findViewById(R.id.category));
        mListView = (ListView) findViewById(R.id.listview);
    }

    @Override
    public void initData() {
        downloadAllData();
        mDatas = new ArrayList<>();
        mMap = new HashMap<>();
        mAdapter = new GetJsonAdapter(this, mDatas);
        mListView.setAdapter(mAdapter);
        mCategory.setText(getString(R.string.get_json_data));
    }

    @Override
    public void initListener() {
        mListView.setOnItemClickListener(this);
    }

    public void refresh(File file) {
        try {
            if (file != null && file.exists()) {
                String data = FileHelper.readFile(file);
                if (!TextUtils.isEmpty(data)) {
                    mJsonAllParse = new JsonAllParse(new JSONObject(data));
                    mDatas.clear();
                    mDatas.addAll(mJsonAllParse.getInfos());
                    Collections.sort(mDatas, new Comparator<AppInfo>() {
                        @Override
                        public int compare(AppInfo o1, AppInfo o2) {
                            return o1.getTaskId() > o2.getTaskId() ? -1 : 1;
                        }
                    });
                    mAdapter.refresh();
                }
            } else {
                downloadAllData();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void selectFile(View view) {
//        Intent intent = new Intent(this, FileDisplayActivity.class);
//        intent.putExtra("from", FROM_GET_JSON_ACTIVITY);
//        startActivityForResult(intent, FROM_GET_JSON_ACTIVITY);
        refresh(new File(FileHelper.BASE_PATH + "/Download/output/netData/all"));
    }

    public void add(View view) {
        Intent intent = new Intent(this, AppInfoActivity.class);
        intent.putExtra("from", FROM_GET_JSON_ACTIVITY);
        startActivityForResult(intent, FROM_GET_JSON_ACTIVITY);
    }

    public void output(View view) {
        if (mJsonAllParse == null) {
            ToastUtils.toast(this, getString(R.string.please_get_all_json_data));
            return;
        }
        boolean isOutput = false;
        AppLayout appLayout = new AppLayout();
        switch (view.getId()) {
            case R.id.all:
                Log.i("ljh", "all");
                if (mJsonAllParse == null) {
                    ToastUtils.toast(this, getString(R.string.please_get_all_json_data));
                    return;
                }
                mJsonAllParse.setInfos(mDatas);
                isOutput = FileHelper.writeFile(mJsonAllParse.toString(), "/all");
                break;
            case R.id.software:
                output(OUTPUT_SOFTWARE, appLayout);
                isOutput = FileHelper.writeFile(appLayout.toString(), "/data/software");
                break;
            case R.id.home:
                output(OUTPUT_HOME, appLayout);
                isOutput = FileHelper.writeFile(appLayout.toString(), "/data/home");
                break;
            case R.id.game:
                output(OUTPUT_GAME, appLayout);
                isOutput = FileHelper.writeFile(appLayout.toString(), "/data/game");
                break;
        }
        ToastUtils.toast(this, getString(isOutput ? R.string.output_success : R.string.output_fail));
    }

    public void output(int type, AppLayout appLayout) {
        sortDatas();
        appLayout.setResult(200);
        appLayout.setMessage("OK");
        List<AppLayout.AppLayoutInfo> appLayoutInfos = new ArrayList<>();
        appLayout.setAppLayoutInfos(appLayoutInfos);
        AppLayout.AppLayoutInfo appLayoutInfo;
        List<AppInfo> appInfos;
        switch (type) {
            case OUTPUT_GAME:
                appInfos = mMap.get(getString(R.string.game));
                appLayoutInfo = new AppLayout.AppLayoutInfo();
                appLayoutInfo.setType(getString(R.string.game));
                appLayoutInfo.setWhole(getString(R.string.whole));
                appLayoutInfo.setAppInfos(appInfos);
                appLayout.getAppLayoutInfos().add(appLayoutInfo);
                break;
            case OUTPUT_SOFTWARE:
                Set<Map.Entry<String, List<AppInfo>>> entries = mMap.entrySet();
                for (Map.Entry<String, List<AppInfo>> entry : entries) {
                    if (entry.getKey().equals(getString(R.string.game))) {
                        continue;
                    }
                    appLayoutInfo = new AppLayout.AppLayoutInfo();
                    appLayoutInfo.setType(entry.getKey());
                    appLayoutInfo.setWhole(getString(R.string.whole));
                    appLayoutInfo.setAppInfos(entry.getValue());
                    appLayout.getAppLayoutInfos().add(appLayoutInfo);
                }
                break;
            case OUTPUT_HOME:
                for (int i = 0; i < 3; i++) {
                    appLayoutInfo = new AppLayout.AppLayoutInfo();
                    appLayoutInfo.setWhole(getString(R.string.whole));
                    appInfos = new ArrayList<>();
                    switch (i) {
                        case 0:
                            appLayoutInfo.setType("最新推荐");
                            appInfos.addAll(mDatas.subList(0, Math.min(mDatas.size(), 10)));
                            break;
                        case 1:
                            appLayoutInfo.setType("最受欢迎");
                            appInfos.addAll(mMap.get("图像影音").subList(0, Math.min(mDatas.size(), 3)));
                            appInfos.addAll(mMap.get("网络社交").subList(0, Math.min(mDatas.size(), 4)));
                            break;
                        case 2:
                            appLayoutInfo.setType("最受好评");
                            appInfos.addAll(mMap.get("应用工具").subList(0, Math.min(mDatas.size(), 3)));
                            appInfos.addAll(mMap.get("游戏").subList(0, Math.min(mDatas.size(), 5)));
                            break;
                    }
                    appLayoutInfo.setAppInfos(appInfos);
                    appLayout.getAppLayoutInfos().add(appLayoutInfo);
                }
                break;
        }
    }

    private void sortDatas() {
        mMap.clear();
        for (int i = 0; i < mDatas.size(); i++) {
            AppInfo appInfo = mDatas.get(i);
            String type = appInfo.getType();
            if (!mMap.containsKey(getString(R.string.all))) {
                mMap.put(getString(R.string.all), new ArrayList<AppInfo>());
            }
            if (!appInfo.getType().equals(getString(R.string.game))) {
                mMap.get(getString(R.string.all)).add(appInfo);
            }
            if (mMap.containsKey(type)) {
                mMap.get(type).add(mDatas.get(i));
            } else {
                mMap.put(type, new ArrayList<AppInfo>());
                mMap.get(type).add(mDatas.get(i));
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FROM_GET_JSON_ACTIVITY) {
            switch (resultCode) {
                case FROM_FILE_DISPLAY_ACTIVITY:
                    File file = (File) data.getSerializableExtra("selectFile");
                    mCategory.setText(getString(R.string.category_format, file.getAbsolutePath()));
                    refresh(file);
                case FROM_APP_INFO_ACTIVITY:
                    int position = data.getIntExtra("position", -1);
                    AppInfo appInfo = (AppInfo) data.getSerializableExtra("appInfo");
                    if (position != -1) {
                        mDatas.set(position, appInfo);
                    } else if (appInfo != null) {
                        mDatas.add(0, appInfo);
                    }
                    mAdapter.refresh();
                    break;
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent intent = new Intent(GetJsonActivity.this, AppInfoActivity.class);
        intent.putExtra("position", position);
        intent.putExtra("appInfo", mDatas.get(position));
        intent.putExtra("from", FROM_GET_JSON_ACTIVITY);
        startActivityForResult(intent, FROM_GET_JSON_ACTIVITY);
    }
}
